import { useEffect, useState } from 'react'
import styled from 'styled-components'

const Wrapper = styled.div`
  .btn-light {
    width: 30px;
  }
  .number {
    display: inline-block;
    width: 30px;
    text-align: center;
  }
`

export default function Step(props) {
  const onBtnHandler = n => {
    if (props.num + n >= 1) {
      props.onNumChange && props.onNumChange(props.num + n)
    }
  }

  // 控制“自减”按钮的禁用状态
  const [isDisabled, setDisabled] = useState(() => props.num <= 1)
  useEffect(() => {
    setDisabled(props.num <= 1)
  }, [props.num])

  return (
    <Wrapper>
      <button type="button" className="btn btn-light btn-sm" disabled={isDisabled} onClick={() => onBtnHandler(-1)}>
        -
      </button>
      <span className="number">{props.num}</span>
      <button type="button" className="btn btn-light btn-sm" onClick={() => onBtnHandler(1)}>
        +
      </button>
    </Wrapper>
  )
}
